package com.maxjay.component.simplelist.service.impl;

import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Component;

import com.maxjay.component.simplelist.model.QueryConditionField;
import com.maxjay.component.simplelist.model.QueryListField;
import com.maxjay.component.simplelist.model.QueryScheme;
import com.maxjay.component.simplelist.service.QuerySqlProcessor;

@Component
public class QuerySqlProcessorImpl implements QuerySqlProcessor {
	
	private static final String BETWEEN_START_POSTFIX = "_START";
	private static final String BETWEEN_END_POSTFIX = "_END";
	
	@Override
	public String getSchemeQuerySql(QueryScheme queryScheme, Map<String, Object> queryParams) {
		String querySql = getQuerySql(queryScheme) + getConditionSql(queryScheme, queryParams);
		return querySql;
	}
	
	private String getQuerySql(QueryScheme queryScheme) {
		StringBuilder sb = new StringBuilder();
		sb.append("SELECT ");
		int i = 1;
		List<QueryListField> fieldList = queryScheme.getListFields();
		for (QueryListField queryListField : fieldList) {
			sb.append(queryListField.getEntityField().getName());
			if (i < fieldList.size()) {
				sb.append(",");
			}
			i++;
		}
		sb.append(" FROM ").append(queryScheme.getEntity().getTabName()).append(" WHERE 1=1 ");
		return sb.toString();
	}
	
	private String getConditionSql(QueryScheme queryScheme, Map<String, Object> queryParams) {
		if (queryParams == null || queryParams.size() == 0) {
			return "";
		}
		StringBuilder sb = new StringBuilder();
		for (QueryConditionField queryField : queryScheme.getConditionFields()) {
			String queryFieldName = queryField.getEntityField().getName().toUpperCase();
			switch (queryField.getCompareType()) {
			case EQUAL:
				if (queryParams.get(queryFieldName) != null) {
					sb.append(" AND ").append(queryFieldName).append("=:").append(queryFieldName);
				}
				break;
			case LIKE:
				if (queryParams.get(queryFieldName) != null) {
					sb.append(" AND ").append(queryFieldName).append(" LIKE '%").append((String)queryParams.get(queryFieldName))
						.append("%'");
//					sb.append(" AND ").append(queryFieldName).append(" LIKE :").append(queryFieldName);
//					String likeValue = "%" + (String)queryParams.get(queryFieldName) + "%";
//					queryParams.put(queryFieldName, likeValue);
				}
				break;
			case BETWEEN:
				if (queryParams.get(queryFieldName + BETWEEN_START_POSTFIX) != null) {
					sb.append(queryFieldName).append(" >= :").append(queryFieldName).append(BETWEEN_START_POSTFIX).append(" AND ");
				}
				if (queryParams.get(queryFieldName + BETWEEN_END_POSTFIX) != null) {
					sb.append(queryFieldName).append(" < :").append(queryFieldName).append(BETWEEN_END_POSTFIX);
				}
				break;
			default:
				break;
			}
		}
		return sb.toString();
	}

}
